package com.shop.controller;

import com.shop.base.BaseController;
import com.shop.result.ResultVO;
import com.shop.util.EmailUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/email")
public class EmailController extends BaseController {

    private final StringRedisTemplate redisTemplate;

    public EmailController(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 发送验证码邮件
     */
    @GetMapping("/send")
    public String sendEmail(@RequestParam("email") String email) {
        if (email == null || email.isEmpty()) {
            return "邮箱地址不能为空";
        }
        if (!isValidEmail(email)) {
            return "邮箱地址格式不正确";
        }

        // 生成6位验证码
        String authCode = generateAuthCode();

        try {
            EmailUtils.sendEmail(email, authCode);
            // 将验证码存入 Redis，并设置5分钟过期
            redisTemplate.opsForValue().set("auth_code:" + email, authCode, 5, TimeUnit.MINUTES);
            return "验证码邮件已发送至：" + email;
        } catch (Exception e) {
            return "邮件发送失败：" + e.getMessage();
        }
    }

    /**
     * 验证用户输入的验证码是否正确
     */
    @GetMapping("/verify")
    public ResultVO<String> verifyEmailCode(@RequestParam("email") String email,
                                           @RequestParam("code") String inputCode) {
        if (email == null || inputCode == null) {
            return success(500,"邮箱或验证码不能为空");
        }

        String key = "auth_code:" + email;
        String storedCode = redisTemplate.opsForValue().get(key);

        if (storedCode == null) {
            return success(500,"验证码已过期或不存在");
        }

        if (inputCode.equals(storedCode)) {
            return success(200,"验证码正确");
        } else {
            return success(500,"验证码错误");
        }
    }

    /**
     * 邮箱格式校验
     */
    private boolean isValidEmail(String email) {
        String emailRegex = "^[a-zA-Z0-9_\\-\\.]+@[a-zA-Z0-9_\\-]+(\\.[a-zA-Z0-9_\\-]+)+$";
        return email != null && email.matches(emailRegex);
    }

    /**
     * 生成6位数字验证码
     */
    private String generateAuthCode() {
        int min = 100000;
        int max = 999999;
        return String.valueOf((int) (Math.random() * (max - min)) + min);
    }
}
